<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\index\model\finance;

/**
 * Description of GameModel
 *
 * @author SoChishun
 */
class RechargeModel extends \app\index\model\BaseModel {

    //put your code here
    protected $table = 't_finance_recharge';
    protected $autoWriteTimestamp = 'timestamp';
    protected $updateTime = false;

    public function saveRecharge($data, $user_id,$payprefix,$pay_channel) {
        $rule = [
            'amount' => 'require|number|token'
        ];
        $message = [
            'amount.require' => '金额未填写',
            'amount.number' => '金额无效',
            'amount.token' => '表单来源无效',
        ];
        $validate = \think\Validate::make($rule, $message);
        if (!$validate->check($data)) {
            $error = $validate->getError();
            return ['success' => false, 'message' => $error];
        }
        // 读取游戏配置
        $gameconf = \app\index\model\ConfModel::get(1);
        if (null == $gameconf) {
            $error = '倍率未配置，请联系管理员!';
            return ['success' => false, 'message' => $error];
        }

        $out_trade_no =$payprefix. date('YmdHis') . (rand(1000, 9999)) . rand(1, 9);
        $saveData = ['amount' => $data['amount'],
            'currency' => $data['amount'] * $gameconf['currency_rate'], // 1元=10竞猜币
            'user_id' => $user_id,
            'out_trade_no' => $out_trade_no,
            'pay_channel'=>$pay_channel,
        ];
        if (!$this->save($saveData)) {
            $error = $this->getError();
            return ['success' => false, 'message' => $error];
        }
        return ['success' => true, 'message' => $saveData];
    }

    public function rechargeConfirm($out_trade_no, $user_id) {
        if (!$out_trade_no) {
            return ['success' => false, 'message' => '交易单号无效'];
        }
        $recharge = $this->get(['out_trade_no' => $out_trade_no]);
        if (null == $recharge) {
            return ['success' => false, 'message' => '交易记录不存在'];
        }
        if ($recharge->status == 1) {
            return ['success' => false, 'message' => '重复操作,记录已处理'];
        }
        $recharge->save(['status' => 1]);
        \app\index\model\UserModel::where(['id' => $user_id])->setInc('currency', $recharge->currency); // 1元=10竞猜币  
        return ['success' => true, 'message' => ''];
    }

    public function getStatusTextAttr() {
        switch ($this->status) {
            case 0:
                return '未支付';
            case 1:
                return '已支付';
        }
    }

}
